﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Reflection;//assembly
using System.IO;
using System.Security.Permissions;
using System.Windows.Forms;
using System.Configuration;
using System.Diagnostics;


namespace BrasilSolutions
{      
    public partial class frmMenu : Form
    {
        public frmMenu()
        {
            InitializeComponent();
        }

        #region VALIDAÇÕES

        /// <summary>
        /// Captura o nó que foi clicado e abre o formulario correspondente
        /// atraves da dll instanciada(instancia automaticamente em tempo de execucao
        /// object MyObj = ass.CreateInstance) 
        /// (node.SelectedNode.Text.Trim())busca o nome do formulario dentro da dll 
        /// e abre este formulario;
        /// O nome da dll sempre será o mesmo nome do nó pai(nó pai Administrativo = dll Administrativo)
        /// (nó pai compras = dll compras)
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        ///        
        private void trvMenu_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            frmLogin f = new frmLogin();
            f.Show();

            Type t = Type.GetType("frmLogin.cs");
            /* Type t = Type.GetType("frmLogin");
            
             if (t != null)
             {

                 System.Windows.Forms.Form f =

                 (System.Windows.Forms.Form)Activator.CreateInstance(t);

                 f.Show();
             }
             */
            //Screen Srn = Screen.PrimaryScreen;
            //int tempHeight = Srn.Bounds.Height;
            //int tempWidth = Srn.Bounds.Width;
            //int largura = (tempWidth - trvMenu.Width) - (this.Width - tempWidth) + this.ActiveControl.Margin.Left + this.ActiveControl.Margin.Right;
            //int altura = (trvMenu.Height - tspBotoes.GripRectangle.Width);
            //largura = Convert.ToInt16(largura - ((largura / 100) * 0.5)); //Usado para ajustar corretamente no monitor
            //altura = Convert.ToInt16(altura - ((altura / 100) * 0.5));//Usado para ajustar corretamente no monitor
            //DataTable _dt = new DataTable();

            //TreeView node = (TreeView)sender;

            //if (string.IsNullOrEmpty(node.Text) && node.SelectedNode != null)
            //{
            //    try
            //    {
            //        Classes.Administrativo.clsMenu menu = new Classes.Administrativo.clsMenu();
            //        DataTable dt = new DataTable();
            //        _dt = menu.RetornaNomeForm(node.SelectedNode.Text.Trim());

            //        if (_dt.Rows[0]["Mnu_Nome_tela"].ToString() != string.Empty)
            //        {
            //            Assembly ass = null;
            //            object obj = new object();
            //            //string path = Application.StartupPath;
            //            //string[] dir = Directory.GetFiles(caminho.Trim(), _NomeDll[0] + ".dll");
            //            //string args = dir[0];

            //            //string ClasstoInstantiate = _NomeDll + "." + _dt.Rows[0]["Mnu_NomeForm"].ToString().Trim();
            //            //Type classType = Type.GetType(ClasstoInstantiate);
            //            //MyObj = Activator.CreateInstance(classType);

            //            Assembly.LoadFrom("frmLogin");
            //            ass = Assembly.LoadFrom("frmLogin");
            //            obj = ass.CreateInstance("frmLogin");
            //            //MyObj = ass.CreateInstance(_NomeDll[0] + "." + _NomeDll[1].Trim());

            //            bool _achou = false;
            //            foreach (Form item in MdiChildren)
            //            {
            //                if (item.Name == "frmLogin")
            //                {
            //                    _achou = true;
            //                    item.Focus();
            //                }
            //            }
            //            if (_achou.Equals(false))
            //            {
            //                Form frm = (Form)obj;
            //                frm.MdiParent = this;
            //                frm.Width = largura;
            //                frm.Height = altura;

            //                frm.Show();
            //                frm.Location = new Point(trvMenu.Width, 0);

            //                //this.tspBotoes.Enabled = true;
            //            }


            //        }
            //        //else
            //        //{
            //        //    MessageBox.Show("O menu " + _dt.Rows[0]["Mnu_Descricao"].ToString() + " esta com problema no Cadastro!!");
            //        //}
                                
            //    }
            //    catch (Exception ex)
            //    {
            //        MessageBox.Show("Ocorreu um erro Ao executar :" + _dt.Rows[0]["Mnu_Descricao"].ToString() + "! Erro: " + ex.ToString());
            //    }
            //    finally
            //    {
            //        _dt.Dispose();
            //    }
            //}
            t = Type.GetType("BrasilSolutions.frmLogin.cs");
            Assembly ass = Assembly.LoadFrom("teste");
            Object MyObj = ass.CreateInstance("frmLogin.cs");
        }

        public void CarregaMenu()
        {
            DataTable dt = new DataTable();
            Classes.Administrativo.clsUsuario u = new Classes.Administrativo.clsUsuario();
            dt = u.RetornaMenu(1);
            trvMenu.Nodes.Clear();
            if (dt != null && dt.Rows.Count > 0)
            {
                Classes.Administrativo.clsMenu m = new Classes.Administrativo.clsMenu();
                m.Popula_TreeMenu2(trvMenu, dt, true);
            }

        }

        //Carrega o treeview com as permissoes do usuario logado
        private void Menu_Shown(object sender, EventArgs e)
        {
            try
            {
                CarregaMenu();
            }
            catch (Exception ex)
            {
                MessageBox.Show ("Ocorreu um erro:" + ex.Message);
            }
        }

        //Valida o ENTER no treeview
        private void trvMenu_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                trvMenu_MouseDoubleClick(trvMenu, null);
            }
        }

        /// <summary>
        /// Define as teclas de atalho utilizadas em frmMenu
        /// Tecla F12 utilizada para fazer Logoff no sistema;
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void frmMenu_KeyDown(object sender, KeyEventArgs e)
        {
            switch (e.KeyCode)
            { 
                case Keys.F12:
                    if (MessageBox.Show("Realizar Logoff?", "Logoff",
                        MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                    {                   
                        this.Dispose();                                       
                        frmLogin f = new frmLogin();
                        f.ShowDialog();
                    }                    
                    break;   
            }
        }
        
        private void frmMenu_FormClosing(object sender, FormClosingEventArgs e)
        {
            if ((MessageBox.Show("Sistema em execução!!! \nDeseja Sair?", "Sair",
                MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No))
            {
                e.Cancel = true;
            }
        }
        
        #endregion 

        private void frmMenu_Load(object sender, EventArgs e)
        {
            try
            {

            }
            catch (Exception ex)
            {
                MessageBox.Show("Problemas ocorridos durante o carregamento do Menu! Erro: " + ex.Message);
            }
        }

        private void trvMenu_MouseHover(object sender, EventArgs e)
        {
            TreeNode selNode = (TreeNode)trvMenu.GetNodeAt(trvMenu.PointToClient(Cursor.HotSpot));
        }

        private void trvMenu_NodeMouseHover(object sender, TreeNodeMouseHoverEventArgs e)
        {
            TreeNode selNode = (TreeNode)trvMenu.GetNodeAt(trvMenu.PointToClient(Cursor.HotSpot));
        }
    }
}
